package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.SelectVo;
import com.zb.entity.ZjCodeBatchGoods;
import com.zb.extend.CodeBatchGoodsExtend;
import com.zb.mapper.ZjCodeBatchGoodsMapper;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.vo.CodeBatchGoodsVo;
import com.zb.vo.CodeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 编码批次商品表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-09-07
 */
@Service
public class ZjCodeBatchGoodsServiceImpl extends ServiceImpl<ZjCodeBatchGoodsMapper, ZjCodeBatchGoods> implements ZjCodeBatchGoodsService {
    @Resource
    private ZjCodeBatchGoodsMapper codeBatchGoodsMapper;

    // 保存批次编码商品
    @Override
    public void save(Long custAccId, Long codeBathId, List<CodeVo> codeVos) {
        List<ZjCodeBatchGoods> batchGoodsList = new ArrayList<>();
        ZjCodeBatchGoods batchGoods = null;
        for (CodeVo codeVo : codeVos) {
            batchGoods = new ZjCodeBatchGoods();
            BeanUtils.copyProperties(codeVo, batchGoods);
            batchGoods.setId(IdWorker.getId());
            batchGoods.setCustAccId(custAccId);
            batchGoods.setBatchId(codeBathId);
            batchGoodsList.add(batchGoods);

            codeVo.setBatchGoodsId(batchGoods.getId());
        }
        this.saveBatch(batchGoodsList);
    }

    // 根据批次编码ID获取批次编码商品数据列表
    @Override
    public Map<String, Object> codeBatchGoodsPageSelect(Long custAccId, Long batchId, SelectVo selectVo) {
        PageUtil.setPageLimit(selectVo);
        long count = codeBatchGoodsMapper.codeBatchGoodsPageSelectCount(batchId, selectVo);
        if (count <= 0) {
            return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), count, new ArrayList<>());
        }
        List<CodeBatchGoodsExtend> codeBatchGoodsExtendList = codeBatchGoodsMapper.codeBatchGoodsPageSelect(batchId, selectVo);
        return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), count, codeBatchGoodsExtendList.stream().map(goods -> {
            CodeBatchGoodsVo vo = new CodeBatchGoodsVo();
            BeanUtil.copyProperties(goods, vo);
            vo.setBrand(goods.getGoodsBrand());
            return vo;
        }).toList());
    }

    // 根据批次ID获取批次编码商品信息
    @Override
    public List<ZjCodeBatchGoods> getByBatchId(Long batchId) {
        QueryWrapper<ZjCodeBatchGoods> wrapper = new QueryWrapper<>();
        wrapper.select("id", "goods_id", "goods_spec_id", "qty", "warranty_day");
        wrapper.eq("batch_id", batchId);
        return this.list(wrapper);
    }
}
